<template>
  <CommonPage>
    <MeCrud
      ref="$table"
      v-model:query-items="queryItems"
      :scroll-x="1200"
      :columns="columns"
      :get-data="api.read"
    >
      <MeQueryItem label="文件名" :label-width="50">
        <n-input
          v-model:value="queryItems.name"
          type="text"
          placeholder="请输入文件名"
          clearable
        />
      </MeQueryItem>
    </MeCrud>
  </CommonPage>
</template>

<script setup>
import { CommonPage, MeCrud, MeQueryItem } from '@/components'
import { useCrud } from '@/composables'
import { NButton } from 'naive-ui'
import { useTemplateRef } from 'vue'
import api from './api'

defineOptions({ name: 'ExcelList' })

const $table = useTemplateRef('$table')
const queryItems = ref({})

onMounted(() => {
  $table.value?.handleSearch()
})

const { handleDelete } = useCrud({
  name: '登录日志',
  doDelete: api.delete,
  refresh: () => $table.value?.handleSearch(),
})

const columns = [
  { title: 'ID', key: 'id', width: 80 },
  { title: '文件名', key: 'object_name' },
  { title: '文件大小', key: 'size_info' },
  { title: '存储路径', key: 'storage_path' },
  { title: '创建时间', key: 'created_at' },
  {
    title: '操作',
    key: 'actions',
    align: 'right',
    hideInExcel: false,
    render(row) {
      return [
        h(
          NButton,
          {
            size: 'small',
            text: true,
            type: 'primary',
            onClick: () => exportBinaryToXLSX(row.full_url),
          },
          {
            default: () => '下载',
            icon: () => h('i', { class: 'i-material-symbols:delete-outline text-14' }),
          },
        ),
        h(
          NButton,
          {
            size: 'small',
            text: true,
            type: 'primary',
            onClick: () => handleDelete([row.id], row.object_name),
          },
          {
            default: () => '删除',
            icon: () => h('i', { class: 'i-material-symbols:delete-outline text-14' }),
          },
        ),
      ]
    },
  },
]

function exportBinaryToXLSX(full_url) {
  const a = document.createElement('a')
  a.href = full_url
  a.download = 'exported_file.xlsx'
  document.body.appendChild(a)
  a.click()
  document.body.removeChild(a)
  window.URL.revokeObjectURL(full_url)
}
</script>
